package xin.petstore.framework.web.sitemesh;

import java.util.ArrayList;
import java.util.List;

import org.sitemesh.DecoratorSelector;
import org.sitemesh.builder.BaseSiteMeshFilterBuilder;
import org.sitemesh.config.ObjectFactory;
import org.w3c.dom.Element;

public class XmlFilterConfigurator extends XmlConfigurator {
    private final Xml xml;

    public XmlFilterConfigurator(ObjectFactory objectFactory, Element siteMeshElement) {
        super(objectFactory, siteMeshElement);
        this.xml = new Xml(siteMeshElement);
    }

    public void configureFilter(BaseSiteMeshFilterBuilder builder, String localPath) {
        setRemoteFilePath(localPath);

        configureCommon(builder);

        String customDecoratorSelector = this.xml.child("decorator-selector").text();
        if (customDecoratorSelector != null) {
            builder.setCustomDecoratorSelector((DecoratorSelector) getObjectFactory().create(customDecoratorSelector));
        }

        String includeErrorPagesString = this.xml.child("include-error-pages").text("false");
        if (("true".equals(includeErrorPagesString)) || ("1".equals(includeErrorPagesString))) {
            builder.setIncludeErrorPages(true);
        }

        for (Xml mapping : this.xml.children("mapping")) {
            String path = mapping.child("path").text(mapping.attribute("path", "/*"));
            if ((isTrue(mapping.attribute("exclude"))) || (!mapping.children("exclude").isEmpty())) {
                builder.addExcludedPath(path);
            }

        }

        List mimeTypeTags = this.xml.children("mime-type");
        if (!mimeTypeTags.isEmpty()) {
            Object mimeTypes = new ArrayList();
            for (Xml mimeTypeTag : mimeTypeTags) {
                ((List) mimeTypes).add(mimeTypeTag.text());
            }
            builder.setMimeTypes((List) mimeTypes);
        }
    }

    private boolean isTrue(String string) {
        String lower = string == null ? "" : string.trim().toLowerCase();
        return (lower.equals("true")) || (lower.equals("1")) || (lower.equals("yes"));
    }
}

